<template>
  <div>
    <div ref="chart" style="width:auto;   height: 50vh;;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'BarChart',
  props: {
    data: {
      type: Object,
    },
    title: {
      type: String
    }
  },
  data() {
    return {
      chart: null,
      option: {
        title: {
          text: '所属知识点试题数'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: 'Direct',
            type: 'bar',
            barWidth: '60%',
            data: [10, 52, 200, 334, 390, 330, 220]
          }
        ]
      }
    };
  },
  mounted() {
    this.initChart()
    this.observeChartResize()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  updated() {
    this.handleResize()
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      // this.option.xAxis[0].data = this.data.pointContentArray
      // this.option.series[0].data = this.data.qsCntArray
      // this.$nextTick = (() => {
      this.chart.setOption(this.option)
      // })
      // this.updateChart()
      // Optional: Handle window resize
      window.addEventListener('resize', this.handleResize);
    },
    updateChart() {
      this.option.xAxis[0].data = this.data.pointContentArray
      this.option.series[0].data = this.data.qsCntArray
      this.chart.setOption(this.option)
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    observeChartResize() {
      // 如果浏览器支持 ResizeObserver
      if (typeof ResizeObserver !== 'undefined') {
        this.resizeObserver = new ResizeObserver(() => {
          if (this.chart) {
            this.chart.resize(); // 调整图表大小
          }
        });
        this.resizeObserver.observe(this.$refs.chart); // 监听容器
      } else {
        // 如果不支持，降级使用 window.resize
        window.addEventListener('resize', this.handleResize);
      }
    }
  }
};
</script>
